package servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import model.RotationImg;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.RotationService;
import service.impl.RotationServiceImpl;
import utils.BaseServlet;
import utils.DateUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description:
 * @Author one world
 * @Date 2020/9/24 0024 15:06
 */
@WebServlet("/rotation")
public class RotationServlet extends BaseServlet {
    private static final Logger logger = LoggerFactory.getLogger(RotationServlet.class);
    private RotationService service = new RotationServiceImpl();

    public void getImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<RotationImg> imgs = service.findAll();
        String result = JSONArray.toJSONString(imgs);
        PrintWriter out = response.getWriter();
        out.write(result);
        out.close();
    }

    public void update(HttpServletRequest request,HttpServletResponse response){

        // 创建磁盘工厂
        FileItemFactory factory = new DiskFileItemFactory();
        // 创建处理工具
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置编码
        upload.setHeaderEncoding("UTF-8");
        // 解析
        List<FileItem> items = null;
        RotationImg img = new RotationImg();
        String path = request.getServletContext().getRealPath("/images");
        try {
            items = upload.parseRequest(request);
            for(FileItem item :items){
                if(item.isFormField()){
                    String name = item.getFieldName();
                    //中文参数乱码问题解决
                    String value = item.getString("utf-8");
                    if(name!=null&&value!=null){
                      if(name.equals("id")){
                         img.setId(Integer.parseInt(value));
                      }else if(name.equals("name")){
                         img.setName(value);
                      }else if (name.equals("url")){
                         img.setUrl(value);
                      }else if(name.equals("date")){
//                         img.setDate(DateUtil.new Date(value),"yyyy-MM-dd HH:mm:ss"));
                          img.setDate(DateUtil.toDate(value,"yyyy-MM-dd HH:mm:ss"));
                          System.out.println("转化后的时间为："+img.getDate());
                      }else if (name.equals("href")){
                          img.setHref(value);
                      }
                    }
                }else{
                    //防文件重名
                    String fileName = UUID.randomUUID()+item.getName();
                    item.write(new File(path,fileName));
                    img.setUrl("../images/"+fileName);
                }

            }
            service.update(img);

        }catch (FileUploadException | UnsupportedEncodingException e){
           logger.error("轮播图修改异常",e);
        } catch (Exception e) {
            logger.error("轮播图修改异常",e);
        }
    }

    public void delete(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String idStr = request.getParameter("id");
        if(idStr==null||idStr.equals("")){
            return;
        }
        int id = Integer.parseInt(idStr);
        String msg = "FAILED";
        if(service.del(id)){
            msg = "SUCCESS";
        }
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(msg));
        out.close();
    }

    public void add(HttpServletRequest request,HttpServletResponse response){
        // 创建磁盘工厂
        FileItemFactory factory = new DiskFileItemFactory();
        // 创建处理工具
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置编码
        upload.setHeaderEncoding("UTF-8");
        // 解析
        List<FileItem> items = null;
        RotationImg img = new RotationImg();
        String path = request.getServletContext().getRealPath("/images");
        try {
            items = upload.parseRequest(request);
            for(FileItem item :items){
                if(item.isFormField()){
                    String name = item.getFieldName();
                    //中文参数乱码问题解决
                    String value = item.getString("utf-8");
                    if(name!=null&&value!=null){
                        if(name.equals("id")){
                            img.setId(Integer.parseInt(value));
                        }else if(name.equals("name")){
                            img.setName(value);
                        }else if (name.equals("url")){
                            img.setUrl(value);
                        }else if(name.equals("date")){
//                         img.setDate(DateUtil.new Date(value),"yyyy-MM-dd HH:mm:ss"));
                            img.setDate(DateUtil.toDate(value,"yyyy-MM-dd HH:mm:ss"));
                            System.out.println("转化后的时间为："+img.getDate());
                        }else if (name.equals("href")){
                            img.setHref(value);
                        }
                    }
                }else{
                    //防文件重名
                    String fileName = UUID.randomUUID()+"";
                    item.write(new File(path,fileName));
                    img.setUrl("../images/"+fileName);
                }

            }
            service.add(img);

        }catch (FileUploadException | UnsupportedEncodingException e){
            logger.error("轮播图添加异常",e);
        } catch (Exception e) {
            logger.error("轮播图添加异常",e);
        }
    }
    public void getImgById(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String idStr = request.getParameter("id");
        if(idStr==null||idStr.equals("")){
            return;
        }
        int id = Integer.parseInt(idStr);
        RotationImg img = service.findById(id);
        System.out.println(img);
        response.getWriter().write(JSON.toJSONString(img));
        response.getWriter().close();
    }
}
